Ext.namespace("Ext.un");

Ext.un.ProgramaTrigger = function(config){
	config || (config = {});
	if(!config.menuPanel){
		this.menuPanel = new Ext.Panel({
							layout:'column',
							items:[]
						});
	}
	if(!config.sm){
		config.sm = new Ext.grid.CheckboxSelectionModel({
						menuPanel : this.menuPanel,
						onRefresh : function(){
					        var ds = this.grid.store,index,
					            s = this.getSelections();
					            
					        for(var i=0,len = s.length; i < len; i++){
					            var r = s[i];
					            if((index = ds.indexOfId(r.id)) != -1){
					            	this.grid.getView().onRowSelect(index);
					            }
					        }
					        if(s.length != this.selections.getCount()){
					            this.fireEvent('selectionchange', this);
					        }
					    },
					    selectRow : function(index, keepExisting, preventViewNotify){

					        var recordSel = this.grid.store.getAt(index);
					        if(recordSel ){ //&& !this.isSelected(index)
					        	this.superclass().selectRow.call(this,index, keepExisting, preventViewNotify);
						        this.appendSelectContent(recordSel);
						        this.menuPanel.doLayout();
					        }
					    },
					    appendSelectContent:function(record){
					    	if(!this.hasSelect(record)){
						    	var panel = this.createSelInfo(record);
						    	this.menuPanel.add(panel);
					    	}
					    },
					    createSelInfo:function(record){
					    	return new Ext.Panel({
					    		id:'p_'+record.data.id,
					    		html:record.data.name+"&nbsp&nbsp"
					    	});
					    },
					    hasSelect:function(record){
					    	var objs = this.menuPanel.findBy(function(c){
					    		var id = c["id"],name = c["name"]
					    		if(id.indexOf("p_") >= 0){
					    			id = id.substring(2);
					    		}
					    		if(id == record.data.id){
					    			return true;
					    		}
					    	});
					    	return objs.length >0?true:false;
					    },
					    deselectRow : function(index, preventViewNotify){
					        this.superclass().deselectRow.call(this,index, preventViewNotify);
					        var record = this.grid.store.getAt(index);
					        var val = record.data.id;
					        this.menuPanel.remove('p_'+val,true);
					    },
					    clearSelections : function(fast){
							 this.superclass().clearSelections.call(this,false);
							 this.cleanAll();
						},
						cleanAll : function(){
							if(this.isLocked()){
								return
							}
							this.grid.getView().removeRows();
						}
					});
	}
	if(!config.store){
		if(config.url){
			config.store = new Ext.un.JsonStoreMutiSelGrid({
			    root:'rows.cell',
			    reader:new Ext.un.JsonReaderMutiSelGrid(),
			    fields:[
			    	{name : 'id',mapping : 'id',type : 'int'},
					{name : 'name',mapping : 'name',type : 'string'}
			    ]
			});
			config.store.proxy = new Ext.common.SyncHttpProxy({url: config.url});
		}else{
			alert("not find grid store with store URL");
		}
	}
	if(!config.cm){
		config.cm = new Ext.grid.ColumnModel([
			config.sm,
			{header:'栏目编号',dataIndex:'id',width:90},
			{header:'栏目名称',dataIndex:'name',width:90}
		]);
	}
	if(!config.triggerForm){
		config.triggerForm = new Ext.FormPanel({
								autoHeight:true,
								labelWidth:60,
								frame:true,
								items:[this.menuPanel,{
										xtype: 'panel',
								        layout: 'column',
								        defaults:{
								        	anchor:'90%'
								        },
								        items: [
								            {
								                xtype: 'panel',
								                layout: 'form',
								                columnWidth: 0.4,
								                items: [
								                    {
								                        xtype: 'textfield',
								                        fieldLabel: '栏目id',
								                        name:'id'
								                    }
								                ]
								            },
								            {
								                xtype: 'panel',
								                layout: 'form',
								                columnWidth: 0.4,
								                items: [
								                    {
								                        xtype: 'textfield',
								                        fieldLabel: '栏目名称',
								                        name:'name'
								                    }
								                ]
								            },
								            {
								                xtype: 'panel',
								                columnWidth: 0.07,
								                items: [
								                    {
								                        xtype: 'button',
								                        text: '搜索',
								                        listeners:{
								                        	"click":{fn:function(){this.onQuery();},scope:this}
								                        }
								                    }
								                ]
								            },
								            {
								                xtype: 'panel',
								                columnWidth: 0.07,
								                items: [
								                    {
								                        xtype: 'button',
								                        text: '确定',
								                        listeners:{"click":{
								                        	fn:function(){
								                        	var records = this.triggerGrid.selModel.getSelections();
								                        	var id = "";
								                        	var name = "";
								                        	for(var i=0,len = records.length;i<len;i++){
								                        		if(id != ""){
								                        			id+= ",";
								                        			name+=',';
								                        		}
									                        	id += records[i].get('id');
									                        	name += records[i].get('name');
								                        	}
								                        	if(this.bindfield){
								                        		Ext.getCmp(this.bindfield).setValue(id);
								                        	}
								                        	this.setValue(name);
								                        	this.hideWin();
								                        },scope:this}
								                      }
								                    }
								                ]
								            },{
								            	xtype:'panel',
								            	columnWidth:0.06,
								            	items:[{
								            		xtype:'button',
								            		text:'重置',
								            		listeners:{
								            			"click":{fn:function(){
								            				this.onReset();
								            			},scope:this}
								            		}
								            	}]
								            }
								        ]
									}]
							});
	}
	
	Ext.un.ProgramaTrigger.superclass.constructor.apply(this,arguments);
}

Ext.extend(Ext.un.ProgramaTrigger,Ext.un.TriggerTemplet,{
	mergeChar:"_",
	noSelected:[],
	menuPanel:null,
	initComponent: function() {
		Ext.un.ProgramaTrigger.superclass.initComponent.call(this);
        this.triggerGrid.store.on("load",function(){
			var records = [];
			for(var i=0;i<this.noSelected.length;i++){
				var record = this.noSelected[i];
				var relRec = this.getRecord(record.data.id, record.data.name);
				if(relRec){
					records[records.length]=relRec;
					this.noSelected.splice(i,1);
					var panel = this.triggerGrid.selModel.createSelInfo(relRec);
					this.menuPanel.remove(panel);
					i--;
				}
			}
			this.doSelectedRow(records);
		},this);
	},
	onTriggerClick:function(){
		this.showContainer.show(this.el);
		this.triggerGrid.selModel.clearSelections();
		this.noSelected = [];
		if(this.triggerGrid.store.getCount()==0){
			this.triggerGrid.store.load({params:{start:0,limit:10}});
		}
		this.onloadData();
	},
	delArrayIndex:function(array,index){
		if(array.length >= index){
			for(var i=index;i<array.length;i++){
				var j= (i===array.length)?i:++i;
				array[i]=array[j];
				array[array.length-1]=null;
			}
		}
	},
	onloadData:function(){
		this.menuPanel.removeAll(true);
		var id = "",name="";
		if(this.bindfield){
			id = Ext.getCmp(this.bindfield).getValue();
			name = this.getValue();
		}
		if(id.length < 1 || name.length < 1){
			return;
		}
		var records = [];
		var idSplit = id.split(',');
		var nameSplit = name.split(',');
		for(var i=0,len = idSplit.length;i<len;i++){
			var values = {};
			values['id']=idSplit[i];
			values['name']=nameSplit[i];
			var record = this.getRecord(idSplit[i],nameSplit[i]);//new Ext.data.Record(values, idSplit[i]);
			if(record == null){
				var noRec = new Ext.data.Record(values, idSplit[i]);
				this.noSelected.push(noRec);
				var panel = this.triggerGrid.selModel.createSelInfo(noRec);
				this.menuPanel.add(panel);
				continue;
			}
			records[records.length]=record;
		}
		this.doSelectedRow(records);
		this.menuPanel.doLayout();
	},
	doSelectedRow:function(records){
		if(records.length > 0){
			this.triggerGrid.selModel.selectRecords(records,true);
		}
	},
	getRecord:function(id,name){
		var record = this.triggerGrid.store.getById(id);
		if(record && record.data.name == name){
			return record;
		}
		return null;
	},
    onCellClick:function(trigger){
    	
    },
    onRowClick:function(trigger){
	    
    }
});
